<?php
namespace app\common\service;
use app\admin\controller\Admin;
use app\common\exception\BackErrorException;
use app\common\model\Admin as AdminModel;
use app\common\model\Banner as BannerModel;
use app\common\util\CacheKey;
use app\common\util\Password as PasswordTool;
use Firebase\JWT\JWT;
use think\facade\Cache;
use think\facade\Db;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/9 0009
 * Time: 21:34
 */
class AdminService{

    public function login($username,$password,$expire){
        $model = new AdminModel();
        $adminUser = $model->where(['username'=>$username,'password'=>PasswordTool::encryptPassword($password)])->find();
        if(empty($adminUser)) return false;
        $time = time();
        $payload = array(
            's'=>$time,
            'exp'=>$time + $expire,
            "id"=>$adminUser['id'],
            't'=>CacheKey::ADMIN,//类型为后台登录
        );
        $jwtKey = env("jwt_key");
        $token = JWT::encode($payload,$jwtKey);

        Cache::delete(CacheKey::ADMIN.'#'.$adminUser['id']);
        //清空上次登录缓存，及时更新登录信息
        return $token;
    }

    public function getList($page,$pageSize,$where){
        $start = ($page - 1) * $pageSize;
        $count = AdminModel::where($where)->count();
        $list = AdminModel::where($where)->order('id','desc')->limit($start,$pageSize)->select();
        return ['total'=>$count,'list'=>$list];
    }

    public function create($data){
        //判断账号
        $exists = AdminModel::where(['username'=>$data['username']])->find();
        if(!empty($exists)){
            throw new BackErrorException("该账号已经存在");
        }
        if(empty($data['password']) || strlen($data['password']) < 6 || strlen($data['password']) > 20){
            throw new BackErrorException("密码不能为空,长度6-20");
        }
        $data['password'] = PasswordTool::encryptPassword($data['password']);

        return AdminModel::create($data);
    }

    public function update($data){
        if(empty($data['id'])){
            throw new BackErrorException("没有选中操作项");
        }
        $exists = AdminModel::where([['username','=',$data['username']],['id','<>',$data['id']]])->find();
        if(!empty($exists)){
            throw new BackErrorException("该账号已经被使用");
        }
        $user = AdminModel::where(['id'=>$data['id']])->find();
        if($user['password'] != $data['password']){
            if(empty($data['password']) || strlen($data['password']) < 6 || strlen($data['password']) > 20){
                throw new BackErrorException("密码不能为空,长度6-20");
            }
            $data['password'] = PasswordTool::encryptPassword($data['password']);
        }
        return AdminModel::update($data,['id'=>$data['id']]);
    }

    public function del($id){
        return AdminModel::destroy(['id'=>$id]);
    }
}
